package com.example.springboot_jxc_0511.conf;

import com.example.springboot_jxc_0511.jxc.common.Constants;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;


@Component
public class ApiInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        System.out.println("拦截1preHandle……");
        // 获取请求的URL
        String url = request.getRequestURI();
        //放行登录页
        if (url.indexOf("/users/toLogin") >= 0 || url.indexOf("/users/login") >= 0) {
            return true;
        }
        // 获取 session
        HttpSession session = request.getSession();
        Object obj = session.getAttribute(Constants.USER_INFO);
        if (obj != null){
            return true;
        }
        // 没有登录且不是登录页面，转发到登录页面，并给出提示错误信息
        request.setAttribute(Constants.ERROR_INFO, "还没登录，请先登录！");
        request.getRequestDispatcher("/users/toLogin").forward(request, response);
        return false;
    }
    @Override
    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o,
                           ModelAndView modelAndView) throws Exception {
        System.out.println("拦截1过程处理些事情postHandle……");
    }

    /**
     * 请求完成:
     * 	执行handler完成之后执行
     *  应用场景：统一异常处理，统一日志处理
     */
    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse,
                                Object o, Exception e) throws Exception {
        System.out.println("拦截1完成afterCompletion......");
    }
}
